﻿using AspNetCore.Host.Hosting;
using AspNetCore.Host.Middleware;
using AspNetCore.Host.Routing;
using Microsoft.Extensions.Logging;

namespace Microsoft.Extensions.DependencyInjection
{
    public class RouteMiddleware : IMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<ExceptionHandlerMiddleware> _logger;

        public RouteMiddleware(
            RequestDelegate next,
            ILogger<ExceptionHandlerMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            try
            {
                var endpoint = context.GetEndpoint();
                if (endpoint != null)
                {
                    await endpoint.Delegate(context);
                }
                else
                {
                    await _next(context);
                }
            }
            catch (Exception ex)
            {

                _logger.LogError(ex.Message, ex);
            }
        }
    }

    public static class RouteMiddlewareExtensions
    {
        public static void UseRouting(this WebApplication app)
        {
            app.Use<RouteMiddleware>();
        }
    }
}
